<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\Comment;
use App\Models\Cookbook;
use App\Models\Notebook;
use App\Services\NotifyService;
use Illuminate\Http\Request;

class CommentController extends BaseController
{

    public $model = Comment::class;


    public function index(Request $request) {
        $this->validate($request, [
            'type' => 'required|in:1,2',
            'entity_id' => 'required'
        ]);
        $entity_id = $request->input('entity_id');
        $parent_id = $request->input('parent_id', 0);
        $type = $request->input('type', 1);
        if ($type == Comment::TYPE_COOKBOOK) {
            $entity = Cookbook::find ($entity_id);
        } else {
            $entity = Notebook::find ($entity_id);
        }
        if (!$entity) {
            $type = 999;
        }
        $list = Comment::withCertain('reply.user', ['nickname', 'avatar_url'])->withCertain('user', ['nickname', 'avatar_url'])
            ->type($type)->where('entity_id', $entity_id)->parentId($parent_id)->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));

        $info = null;
        if ($parent_id) {
            $info = Comment::withCertain('user', ['nickname', 'avatar_url'])->find($parent_id);
        }
        return $this->paginate($list, $info);
    }

    /**
     * 评论
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Throwable
     */
    public function store(Request $request) {
        $this->validate($request, [
            'entity_id' => 'required',
            'message' => 'required',
            'type' => 'required|in:1,2'
        ]);
        $user = $this->getUser();
        $input = $request->input();

        try {
            $id = \DB::transaction(function () use($input, $user){
                if ($input['type'] == Comment::TYPE_COOKBOOK) {
                    $entity_model = new Cookbook();
                } else {
                    $entity_model = new Notebook();
                }
                $entity_result = $entity_model->find($input['entity_id']);
                if (!$entity_result)
                    throw new \Exception("ID对应数据不存在");

                $entity_result->comment_num += 1;
                $entity_result->save();

                if ($parent_id = ($input['comment_id'] ?? 0)) {
                    $comment = Comment::find($parent_id);
                    if (!$comment)
                        throw new \Exception("留言id不存在");
                    $comment->increment('reply_count', 1);
                    if ($comment->parent_id != 0) {
                        $input['reply_to_id'] = $comment->id;
                        $input['parent_id'] = $comment->parent_id;
                    } else {
                        $input['parent_id'] = $parent_id;
                    }
                }
                $input['user_id'] = $user->id;
                $info = $this->model::create($input);
                $id = $info->id;

                if ($input['type'] == Comment::TYPE_NOTEBOOK) {
                    if ($parent_id) {
                        NotifyService::store($input['user_id'], 4, $input['entity_id'], $comment->user_id, $input['message']);
                    } else {
                        NotifyService::store($input['user_id'], 3, $input['entity_id'], $entity_result->user_id, $input['message']);
                    }
                }

                return $id;
            });
            return $this->success($id);
        } catch (\Exception $e) {
            \Log::error($e->getLine());
            return $this->failed($e->getMessage());
        }

    }

    /**
     * 删除
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Throwable
     */
    public function destroy(Request $request)
    {
        $this->validate($request, [
            'comment_id' => 'required',
        ]);
        $id = \request('comment_id');
        $comment = Comment::find($id);
        if (!$comment)
            return $this->failed("评论不存在");
        if ($comment->user_id != $this->getUserId())
            return $this->failed("无权删除");

        $parent_id = $comment->parent_id;
        return \DB::transaction(function () use ($parent_id, $comment) {
            if ($parent_id) {
                $comment->delete();
                Comment::where('id', $parent_id)->increment('reply_count', -1);
            }

            if ($comment->entity_id == Comment::TYPE_COOKBOOK) {
                $entity_model = new Cookbook();
            } else {
                $entity_model = new Notebook();
            }

            $entity_model->where('id', $comment->entity_id)->increment('comment_num', -$comment->reply_count);
            return $this->success($comment->id);
        });
    }


}

